package main

import (
	"fmt"
	"github.com/gogo/protobuf/proto"
	"github.com/micro/go-micro/v2"
	"github.com/micro/go-micro/v2/broker"
	"mqtt/message"
	"github.com/micro/go-plugins/broker/mqtt/v2"
	_ "github.com/micro/go-plugins/broker/mqtt/v2" //init初始化
)
/**
 代理组件-mqtt消息队列
 下载 mqtt: https://activemq.apache.org/
 解压zip启动：\bin\win64\activemq.mq  登陆http://127.0.0.1:8161/ 用户名:amin 密码：admin
 */

/**
 go-micro v2版本：
 protoc compiler：https://github.com/google/protobuf
 go get github.com/micro/micro/v2/cmd/protoc-gen-micro@master
 go get github.com/micri/go-micro/v2
 go get github.com/micro/go-plugins/broker/mqtt/v2 [插件v2版本需独自下载对应版本]
 protoc  --proto_path=. --micro_out=. --go_out=. message.proto
 */
func main() {
	//创建一个微服务
	service := micro.NewService(
		micro.Name("mqtt-server"),
		micro.Version("v1.0.1"),
		micro.Broker(mqtt.NewBroker()),//实例化mqtt broker代理
		)
	service.Init()
	//获取代理实例
	pubSub := service.Server().Options().Broker
	//获取链接
	err := pubSub.Connect()
	if err !=nil {
		panic(err)
	}
	//消息发布
	//sendType1(pubSub,"input")
	sendType2(pubSub,"struct")
	defer pubSub.Disconnect()//关闭链接
}

func sendType1(pubSub broker.Broker,data_type string){
	var msg string
	for{
		fmt.Println("input:")
		fmt.Scan(&msg)
		if msg == "exit"{
			break
		}
		data_msg := broker.Message{
			Header:map[string]string{
				"header-name":"publish",
				"header-version":"v1.0.0",
				"data_type":data_type,
			},
			Body:[]byte(msg),
		}
		err := pubSub.Publish("mqtt-test-msg",&data_msg)
		if err!=nil{
			fmt.Println("消息发布失败！ ",err.Error())
		}else {
			fmt.Println("消息发布成功！\n")
		}
	}
}
func sendType2(pubSub broker.Broker,data_type string){
	student := &message.Student{Name:"ztind",Age:18,Class:"三年二班"}
	data,_ := proto.Marshal(student)
	data_msg := broker.Message{
		Header:map[string]string{
			"header-name":"publish",
			"header-version":"v1.0.0",
			"data_type":data_type,
		},
		Body:data,
	}
	err := pubSub.Publish("mqtt-test-msg",&data_msg)
	if err!=nil{
		fmt.Println("消息发布失败！ ",err.Error())
	}else {
		fmt.Println("消息发布成功！\n")
	}
}